//
//  AppDelegate.m
//  moon
//
//  Created by beyself on 16/6/5.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "AppDelegate.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "SettingViewController.h"
#import "AppViewController.h"
#import "PrivateViewController.h"
#import "ChatListViewController.h"
#import <RongIMKit/RongIMKit.h>
#import "WXApi.h"
#import "UMMobClick/MobClick.h"
#import "UMessage.h"
#import "GuideViewController.h"
#import "WXApiManager.h"

@interface AppDelegate ()<RCIMReceiveMessageDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _mMemberInfo = [[NSMutableDictionary alloc] init];
    [self initSDK:launchOptions];
    
    _newType = -1;
    NSDictionary* message = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (message) {
        NSString *payloadMsg = [[message objectForKey:@"aps"] objectForKey:@"alert"];
        if(payloadMsg && payloadMsg.length)
        {
            if([payloadMsg rangeOfString:@"作业"].length) _newType = 1;
            else if([payloadMsg rangeOfString:@"通知"].length) _newType = 2;
            else if([payloadMsg rangeOfString:@"动态"].length || [payloadMsg rangeOfString:@"赞"].length || [payloadMsg rangeOfString:@"评论"].length) _newType = 0;
            else _newType = 3;
        }
    }
    
    [self showMainView];
    _deviceToken = [[NSMutableString alloc] init];
    
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:nil];
        
        [application registerUserNotificationSettings:notiSettings];
        
    } else{ // ios7
        [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge                                       |UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert)];
    }
    
    self.window.backgroundColor = BG;
    
    return YES;
}

- (void) initSDK:(NSDictionary *)launchOptions
{
    [[RCIM sharedRCIM] initWithAppKey:@"kj7swf8o702m2"];
    [RCIM sharedRCIM].globalConversationAvatarStyle=RC_USER_AVATAR_CYCLE;
    [RCIM sharedRCIM].globalMessageAvatarStyle=RC_USER_AVATAR_CYCLE;
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
    [WXApi registerApp:@"wx1b1c07ed52fbfc12"];
    
    UMConfigInstance.appKey = @"5681349a67e58e45d4001537";
    UMConfigInstance.channelId = @"ylbb";
    [MobClick startWithConfigure:UMConfigInstance];
    
    [UMessage startWithAppkey:@"5681349a67e58e45d4001537" launchOptions:launchOptions];
    [UMessage registerForRemoteNotifications];
    [UMessage setLogEnabled:YES];
}

- (void) refreshNew:(NSString*)num
{
    UITabBarController* tabViewController = (UITabBarController*)self.window.rootViewController;
    UIViewController* subview = tabViewController.viewControllers[1];
    if(num.length && [num intValue] > 0)
    {
        _newChat = [num intValue];
        [subview.tabBarItem setBadgeValue:num];
    }
    else
    {
        _newChat = 0;
        [subview.tabBarItem setBadgeValue:nil];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"receive_msg"  object:nil];
}

- (void) setChatUnread
{
    int left = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
   
    NSString* num = @"";
    if(left) num = [NSString stringWithFormat:@"%d",left];
    [self performSelectorOnMainThread:@selector(refreshNew:) withObject:num waitUntilDone:YES];
}

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left
{
    left = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    
    NSString* num = @"";
    if(left) num = [NSString stringWithFormat:@"%d",left];
    [self performSelectorOnMainThread:@selector(refreshNew:) withObject:num waitUntilDone:YES];
}

- (void) showMainView
{
    [[UINavigationBar appearance] setBarTintColor:BLUE];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    [[UINavigationBar appearance] setTintColor:WHITE];
    
    [[UITabBar appearance] setBarTintColor:WHITE];
//    [[UITabBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:BLUE,UITextAttributeTextColor,nil]];
    [[UITabBar appearance] setTintColor:BLUE];
    
    /*
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:20/255.0 green:155/255.0 blue:213/255.0 alpha:1.0]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];*/
    
    NSString* isLogin = [Utils readDefaultUser:@"isLogin"];
    if(!isLogin || ![isLogin isEqualToString:@"1"])
    {
        GuideViewController* subview = [[GuideViewController alloc] init];
        self.window.rootViewController = subview;
        return;
    }
    
    NSString* username = [Utils readDefaultUser:@"username"];
    NSDictionary* memberInfo = (NSDictionary*)[Utils loadCustomObjectWithKey:LOGIN_INFO];
    if(username && username.length && [memberInfo description].length && memberInfo && memberInfo.count > 0)
    {
        [[RCIM sharedRCIM] connectWithToken:memberInfo[@"im_token"] success:^(NSString *userId) {
            int left = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
            NSString* num = @"";
            if(left) num = [NSString stringWithFormat:@"%d",left];
            
            [self performSelectorOnMainThread:@selector(refreshNew:) withObject:num waitUntilDone:YES];
        } error:^(RCConnectErrorCode status) {

        } tokenIncorrect:^{

        }];
        [_mMemberInfo setDictionary:memberInfo];
        [self initTabview];
    }
    else
    {
        [self initLogin];
    }
}

- (void) initLogin
{
    LoginViewController* subview = [[LoginViewController alloc] init];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:subview];
    self.window.rootViewController = nav;
}

- (void) initTabview
{
    [self.window.rootViewController.view removeFromSuperview];
    
    mTabInit[0] = YES;
    mTabInit[1] = YES;
    mTabInit[2] = YES;
    mTabInit[3] = YES;
    
    NSMutableArray* array = [[NSMutableArray alloc] init];
    
    _mMainViewController = [[MainViewController alloc] init];
    _mMainViewController.title = @"班级圈";
    UITabBarItem* item = [[UITabBarItem alloc] init];
    item.title = @"班级圈";
    _mMainViewController.tabBarItem = item;
    [item setFinishedSelectedImage:[UIImage imageNamed:@"menu1_focus"] withFinishedUnselectedImage:[UIImage imageNamed:@"menu1"]];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:_mMainViewController];
    [array addObject:nav];
    
    ChatListViewController* subview = [[ChatListViewController alloc] init];
    subview.title = @"互动";
    item = [[UITabBarItem alloc] init];
    item.title = @"互动";
    subview.tabBarItem = item;
//    item.image = [UIImage imageNamed:@"menu2"];
    [item setFinishedSelectedImage:[UIImage imageNamed:@"menu2_focus"] withFinishedUnselectedImage:[UIImage imageNamed:@"menu2"]];
    nav = [[UINavigationController alloc] initWithRootViewController:subview];
    [array addObject:nav];
    
    subview = [[AppViewController alloc] init];
    subview.title = @"应用";
    item = [[UITabBarItem alloc] init];
    item.title = @"应用";
    subview.tabBarItem = item;
    nav = [[UINavigationController alloc] initWithRootViewController:subview];
    [item setFinishedSelectedImage:[UIImage imageNamed:@"menu3_focus"] withFinishedUnselectedImage:[UIImage imageNamed:@"menu3"]];
    [array addObject:nav];
    
    subview = [[SettingViewController alloc] init];
    subview.title = @"我";
    item = [[UITabBarItem alloc] init];
    item.title = @"我";
    subview.tabBarItem = item;
    [item setFinishedSelectedImage:[UIImage imageNamed:@"menu4_focus"] withFinishedUnselectedImage:[UIImage imageNamed:@"menu4"]];
    nav = [[UINavigationController alloc] initWithRootViewController:subview];
    [array addObject:nav];
    
    UITabBarController* tabViewController = [[UITabBarController alloc] init];
    tabViewController.viewControllers = array;
    
    self.window.rootViewController = tabViewController;
}

- (void) showDialog:(NSString*)msg
{
    UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                     message:msg
                                                    delegate:self
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil, nil];
    [dialog show];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                        stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
    [UMessage registerDeviceToken:deviceToken];
    
    [_deviceToken setString:token];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    mTabInit[0] = YES;
    mTabInit[1] = YES;
    mTabInit[2] = YES;
    mTabInit[3] = YES;
    
    if(_isBack)
    {
        _newType = -1;
        if (userInfo) {
            NSString *payloadMsg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
            if(payloadMsg && payloadMsg.length)
            {
                if([payloadMsg rangeOfString:@"作业"].length) _newType = 1;
                else if([payloadMsg rangeOfString:@"通知"].length) _newType = 2;
                else if([payloadMsg rangeOfString:@"动态"].length || [payloadMsg rangeOfString:@"赞"].length || [payloadMsg rangeOfString:@"评论"].length) _newType = 0;
                else if([payloadMsg rangeOfString:@"入校"].length || [payloadMsg rangeOfString:@"离校"].length) _newType = 3;
            }
        }
        
        if(_newType > -1)
        {
            _isBack = NO;
            [self initTabview];
        }
    }
    else{
        [_mMainViewController buttonClick:_mMainViewController.mTabBtn];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSString *error_str = [NSString stringWithFormat: @"%@", error];
    NSLog(@"Failed to get token, error:%@", error_str);
}

- (BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pay_notify" object:nil];
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    int left = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    [UIApplication sharedApplication].applicationIconBadgeNumber = _newMessage + left;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    _isBack = YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pay_notify" object:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [Utils sendHttpLogin];
    
    if(_isBack)
    {
        mTabInit[0] = YES;
        mTabInit[1] = YES;
        mTabInit[2] = YES;
        mTabInit[3] = YES;
        
        _isBack = NO;
        [_mMainViewController buttonClick:_mMainViewController.mTabBtn];
    }
}

- (BOOL) getTabInit:(int)tab
{
    return mTabInit[tab];
}

- (void) setTabInit:(BOOL)result tab:(int)tab
{
    mTabInit[tab] = result;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
